package com.org.controller;


import com.org.model.Administrator;
import com.org.model.User;
import com.org.service.IAdministratorService;
import com.org.service.impl.AdministratorServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author test
 * @since 2021-06-05
 */

@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdministratorController {
    @Autowired
    private IAdministratorService administratorService;
    @Autowired
    private AdministratorServiceImpl serviceImp;

    @PostMapping("/getAdmin")
    public List<Administrator> getAdmin(){
        return administratorService.list();
    }

    @PostMapping("/adminLogin")
    public Map<String,Object> checkUser(@RequestParam(name = "name") String name,
                                        @RequestParam (name = "password") String password){
        Map<String,Object> data = new HashMap<>();
        Administrator admin = serviceImp.getByAccount(name);
        if ( admin!=null ){
            if (admin.getPassword().equals(password)) {
                data.put("code",200);
                data.put("data", admin);
                data.put("msg", "success");
            }else {
                data.put("code",400);
                data.put("msg","密码错误");
            }
        }else {
            data.put("code",400);
            data.put("msg","账号错误");
        }
        return data;
    }

    @PostMapping("/changePassword")
    public Map<String,Object> changePassword(@RequestParam(name = "uid") Integer uid,
                                             @RequestParam(name = "oldpassword") String oldpassword,
                                             @RequestParam(name = "newpassword") String newpassword){
        Map<String,Object> data = new HashMap<>();
        Administrator administrator = serviceImp.getById(uid);
        data.put("code",200);
        if (administrator.getPassword().equals(oldpassword)){
            administrator.setPassword(newpassword);
            boolean check = serviceImp.updateById(administrator);
            if (check){
                data.put("msg","success");
            }else {
                data.put("msg","更新失败");
            }
        }else {
            data.put("msg","旧密码错误");
        }
        return data;
    }


    @PostMapping("/getAdminByAccount")
    public Map<String, Object> getUserByAccount(@RequestParam(name = "name") String name){
        Administrator administrator = serviceImp.getAdminByName(name);
        Map<String,Object> data = new HashMap<>();
        if (administrator!=null){
            data.put("code",200);
            data.put("msg","查询成功");
            data.put("data",administrator);
        }else {
            data.put("code",400);
            data.put("msg","查询失败");
        }
        return data;
    }
}
